<template>
    <picker class="h-picker-wrap" mode="selector" :range="arr" @change="handleChange">
      <text v-if="selectedLabel">{{selectedLabel}}</text>
      <text class="h-picker-select" v-else>请选择</text>
    </picker>
</template>

<script>
export default {
  name: 'hPicker',
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    selector: {
      type: Array,
      default() {
        return []
      }
    }
  },
  inject: {
    hFormItem: {
      from: 'hFormItem',
      default() {
        return null
      }
    }
  },
  data() {
    return {
      selectorChecked: '',
      selectedLabel: ''
    }
  },
  computed: {
    arr() {
      let data = JSON.parse(JSON.stringify(this.selector))
      data = data.map(item => item.label)
      return data
    }
  },
  mounted() {
    let data = JSON.parse(JSON.stringify(this.selector))
    let value = data.find(item => item.value === this.value)?.value || ''
    this.selectorChecked = value
    let label = data.find(item => item.value === this.value)?.label || ''
    this.selectedLabel = label
  },
  methods: {
    handleChange(e) {
      this.selectorChecked = this.selector[e.detail.value]?.value || ''
      this.selectedLabel = this.selector[e.detail.value]?.label || ''
      if(this.hFormItem) {
        this.hFormItem.onFieldChange(this.selectorChecked)
      }
      this.$emit('input', this.selectorChecked)
      this.$emit('change', this.selectorChecked)
    }
  },
  watch: {
    value() {
      let data = JSON.parse(JSON.stringify(this.selector))
      let value = data.find(item => item.value === this.value)?.value || ''
      this.selectorChecked = value
      let label = data.find(item => item.value === this.value)?.label || ''
      this.selectedLabel = label
    }
  }
}
</script>

<style>
.h-picker-wrap {
  flex: 1;
  font-size: 28rpx;
}
.h-picker-select {
  color: #888787;
  font-size: 28rpx;
}
</style>
